import React from 'react'
import PropTypes from 'prop-types'
import { withStyles } from 'material-ui/styles'
import { inject, observer } from 'mobx-react'
import Helmet from 'react-helmet'

import TopicItem from '../topic_item/index'
import TopicListStore from '../../stores/topic_list'

import LoadingStatus from '../loading_status/index'

import ListenScroll from '../listen_scroll/index'
import PostIcon from '../post_icon/index'
import tabTitle from '../../constant/create_title'

@inject((stores) => {
  const store = {
    topicList: stores.topicList,
  }
  return store
})
@observer
class TopicsList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
    }
    this.getMore = this.getMore.bind(this)
    this.page = 1
  }
  componentDidMount() {
    this.getTopicList()
  }
  componentDidUpdate(preProps) {
    if (preProps.tab !== this.props.tab) {
      this.getTopicList()
    }
  }
  getTopicList(page = 1) {
    const { tab, limit } = this.props
    this.setState({
      isLoading: true,
    })
    this.props.topicList.getTopicList(tab, page, limit).then(() => this.setState({
      isLoading: false,

    }))
  }
  getMore() {
    this.page += 1
    const { page } = this
    this.getTopicList(page)
  }
  getAllTopics() {
    let allTopics
    const { topics } = this.props.topicList
    for (let i = 1; i <= this.page; i++) {
      const key = `${this.props.tab}${i}`
      const topicData = topics.get(key)
      const topicList = topicData ? topicData.slice() : []
      allTopics = i === 1 ? topicList : [...allTopics, ...topicList]
    }
    return allTopics
  }
  asyncBootstrap() {
    return new Promise((resolve, reject) => {
      const { tab, limit } = this.props
      this.props.topicList.getTopicList(tab, 1, limit)
        .then(() => resolve(true))
        .catch(reject)
    })
  }
  render() {
    const topics = this.getAllTopics()
    const { isLoading } = this.state
    const { hasMore } = this.props.topicList
    const { tab } = this.props
    const tb = tabTitle(tab, '-CNode中文社区')
    return (
      <ListenScroll
        onBottom={this.getMore}
        isLoading={isLoading}
        hasMore={hasMore}
        hasMoreTips="上滑加载更多"
        noMoreTips="没有更多话题了..."
      >

        { topics && topics.length ?
          <div>
            <Helmet>
              <title>{tb}</title>
            </Helmet>
            {
              topics.map(topic => (
                <TopicItem topic={topic} key={topic.id} />
              ))
            }
            <PostIcon />
          </div>
          :
          <div>
            <LoadingStatus />
          </div>
        }
      </ListenScroll>
    )
  }
}
const style = {
  topicCategory: {
    marginBottom: '0.1rem',
  },
}
export default withStyles(style)(TopicsList)

TopicsList.propTypes = {
  // classes: PropTypes.objectOf(Object),
  topicList: PropTypes.instanceOf(TopicListStore),
  tab: PropTypes.string,
  limit: PropTypes.number,
}

